package com.fary.web.servlet.mvc.method.annotation;

import com.fary.beans.factory.BeanFactory;
import com.fary.core.MethodParameter;
import com.fary.web.context.request.NativeWebRequest;
import com.fary.web.context.request.async.WebAsyncTask;
import com.fary.web.context.request.async.WebAsyncUtils;
import com.fary.web.method.support.HandlerMethodReturnValueHandler;
import com.fary.web.method.support.ModelAndViewContainer;

public class AsyncTaskMethodReturnValueHandler implements HandlerMethodReturnValueHandler {

    private final BeanFactory beanFactory;


    public AsyncTaskMethodReturnValueHandler(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }


    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return WebAsyncTask.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

        if (returnValue == null) {
            mavContainer.setRequestHandled(true);
            return;
        }

        WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) returnValue;
        if (this.beanFactory != null) {
            webAsyncTask.setBeanFactory(this.beanFactory);
        }
        // 调用异步管理器执行任务
        WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(webAsyncTask, mavContainer);
    }

}